<?php

namespace App\Services;

use App\Enums\Gender;
use App\Enums\MatterType;
use App\Enums\ReceptionType;
use App\Enums\Source;
use App\Exceptions\AdminInvalidRequestException;
use App\Jobs\AllocateCustomerMessageJob;
use App\Models\Customer;
use App\Models\Information;
use App\Models\Matter;
use App\Models\MatterReception;
use App\Models\Merchant;
use App\Models\Reception;
use App\Models\ReturnPerformance;
use App\Models\SalePerformance;
use Illuminate\Support\Facades\DB;

class SaleService
{
    //挂号
    public function register(int $customer_id, array $input)
    {
        return DB::transaction(function () use ($input, $customer_id) {
            $customer = Customer::query()->where('id', $customer_id)->lockForUpdate()->first();
            if (Customer::query()->where('phone', $input['phone'])->where('id', '!=', $customer_id)->exists()) {
                throw new AdminInvalidRequestException('手机号已存在');
            }
            if (isset($input['age']) && !is_numeric($input['age'])) {
                throw new AdminInvalidRequestException('请正确填写年龄');
            }
            if (isset($input['gender']) && $input['gender'] == Gender::UNKNOWN) {
                throw new AdminInvalidRequestException('请选择性别');
            }
            if (isset($input['gender']) && !isset($input['province_id'])) {
                throw new AdminInvalidRequestException('请选择地区');
            }
            //保存挂号信息
            $customer->id_card = $input['id_card'] ?: '';
            $customer->disease = $input['disease'] ?: '';
            $customer->doctor_option_id = $input['doctor_option_id'] ?: 0;
            $customer->time_of_appointment = $input['time_of_appointment'] ?: null;
            $customer->consultation = $input['consultation'] ?: null;
            $customer->wechat = $input['wechat'] ?: '';
            $customer->phone = $input['phone'];
            $customer->name = $input['name'];
            $customer->age = $input['age'] ?: 0;
            $customer->gender = $input['gender'];
            $customer->province_id = $input['province_id'] ?? 0;
            $customer->city_id = $input['city_id'] ?? 0;
            $customer->district_id = $input['district_id'] ?? 0;
            $customer->address = $input['address'] ?: '';
            $customer->symptom = $input['symptom'] ?: '';
            $customer->treatment_history = $input['treatment_history'] ?: '';
            $customer->save();
        }, 2);
    }


    /**
     * 销售添加业绩
     * @param int $customer_id
     * @param array $input
     * @return mixed
     */
    public function addPerformance(int $customer_id, array $input): mixed
    {
        return DB::transaction(function () use ($customer_id, $input) {
            $customer = Customer::query()->where('id', $customer_id)->first();
            if (!is_numeric($input['money']) || $input['money'] <= 0) {
                throw new AdminInvalidRequestException('请填写付款金额');
            }
            //保存业绩数据
            SalePerformance::query()->create([
                'customer_id' => $customer->id,
                'user_id' => $customer->sale_user_id,
                'payment_option_id' => $input['payment_option_id'],
                'type' => $input['type'],
                'money' => $input['money'],
                'pay_images' => $input['pay_images'] ? json_encode($input['pay_images']) : '',
                'medication' => $input['medication'] ?: '',
                'treatment' => $input['treatment'] ?: '',
                'bill' => $input['bill'] ?: '',
                'symptom' => $input['symptom'] ?: '',
                'disease' => $input['disease'] ?: '',
                'consultation' => $input['consultation'] ?: null,
                'remark' => $input['remark'] ?: '',
            ]);
            $customer->deal = now();
            $customer->save();
            return true;
        }, 2);
    }

    //补欠款
    public function balance(int $customer_id, array $input)
    {
        return DB::transaction(function () use ($customer_id, $input) {
            $customer = Customer::query()->where('id', $customer_id)->first();

            if (!is_numeric($input['money']) || $input['money'] <= 0) {
                throw new AdminInvalidRequestException('请正确填写尾款金额');
            }

            //保存业绩数据
            SalePerformance::query()->create([
                'customer_id' => $customer->id,
                'user_id' => $customer->sale_user_id,
                'payment_option_id' => $input['payment_option_id'],
                'type' => $input['type'],
                'money' => $input['money'],
                'pay_images' => $input['pay_images'] ? json_encode($input['pay_images']) : '',
                'remark' => $input['remark'] ?: '',
            ]);
        }, 2);
    }

    //添加复诊业绩
    public function addReturnPerformance(int $customer_id, array $input)
    {
        return DB::transaction(function () use ($customer_id, $input) {
            $customer = Customer::query()->where('id', $customer_id)->first();
            if (!is_numeric($input['money']) || $input['money'] <= 0) {
                throw new AdminInvalidRequestException('请填写付款金额');
            }
            if (!is_numeric($input['subsidy']) || $input['subsidy'] < 0) {
                throw new AdminInvalidRequestException('请正确填写大病补助费用');
            }
            //保存业绩数据
            ReturnPerformance::query()->create([
                'customer_id' => $customer->id,
                'user_id' => $customer->return_user_id,
                'disease' => $input['disease'] ?: '',
                'doctor_option_id' => $input['doctor_option_id'],
                'money' => $input['money'],
                'subsidy' => $input['subsidy'],
                'pay_images' => $input['pay_images'] ? json_encode($input['pay_images']) : '',
                'remark' => $input['remark'] ?: '',
                'stage' => $input['stage'],
                'channel' => $input['channel'],
                'delivery' => $input['delivery'] ?: '',
                'drug' => $input['drug'] ?: '',
                'treatment_course' => $input['treatment_course'] ?: '',
                'channel_date' => $input['channel_date'] ?: null,
                'consultation' => $input['consultation'] ?: null,
                'invitation_user_ids' => $input['invitation_user_ids'] ? json_encode($input['invitation_user_ids']) : '',
                'consultant_user_ids' => $input['consultant_user_ids'] ? json_encode($input['consultant_user_ids']) : '',
            ]);
            return true;
        }, 2);
    }

    /**
     * 分配到复诊部
     * @param bool $is_auto
     * @param int $customer_id
     * @param int $return_user_id
     * @return mixed
     */
    public function allocate(bool $is_auto, int $customer_id, int $return_user_id = 0): mixed
    {
        return DB::transaction(function () use ($is_auto, $customer_id, $return_user_id) {
            //需要分配的案件数据
            $customer = Customer::query()->where('id', $customer_id)->lockForUpdate()->first();
            if ($customer->return_user_id) {
                throw new AdminInvalidRequestException('客户已有复诊部接待，请勿重复分配');
            }
            if ($is_auto) {
                //查询出诉讼部/调解部顾问接待设置，然后进行分配
                $service = new ReceptionService(ReceptionType::RETURN_VISIT);
                //获取接待人
                $return_user_id = $service->getReceptionUser();
                if (!$return_user_id) {
                    throw new AdminInvalidRequestException('无可用接待人，请检查复诊部接待设置');
                }
            }
            $customer->return_user_id = $return_user_id;
            $customer->return_time = now();
            $customer->save();
            //增加接待人今日接待量
            Reception::query()
                ->where('user_id', $return_user_id)
                ->increment('today_number');
        }, 2);
    }


    /**
     * 分配到销售部
     * @param bool $is_auto
     * @param int $customer_id
     * @param int $sale_user_id
     * @return mixed
     */
    public function receptionAllocate(bool $is_auto, int $customer_id, int $sale_user_id = 0): mixed
    {
        return DB::transaction(function () use ($is_auto, $customer_id, $sale_user_id) {
            //需要分配的案件数据
            $customer = Customer::query()->where('id', $customer_id)->lockForUpdate()->first();
            if ($customer->sale_user_id) {
                throw new AdminInvalidRequestException('客户已有销售部接待，请勿重复分配');
            }
            if ($is_auto) {
                //查询出诉讼部/调解部顾问接待设置，然后进行分配
                $service = new ReceptionService(ReceptionType::SALE);
                //获取接待人
                $sale_user_id = $service->getReceptionUser();
                if (!$sale_user_id) {
                    throw new AdminInvalidRequestException('无可用接待人，请检查销售部接待设置');
                }
            }
            $customer->sale_user_id = $sale_user_id;
            $customer->sale_time = now();
            $customer->save();
            //增加接待人今日接待量
            Reception::query()
                ->where('user_id', $sale_user_id)
                ->increment('today_number');
        }, 2);
    }
}
